package com.patzn.osgi.tracker.http.core;

import com.patzn.osgi.tracker.http.api.RequestHandler;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class HttpServer {

    private int port = 8080;
    private Map<String, RequestHandler> map = new ConcurrentHashMap<>();
    private volatile boolean running = true;
    private ServerSocket serverSocket;

    public void addHandler(String path, RequestHandler requestHandler) {
        map.put(path, requestHandler);
    }

    public void removeHandler(String path) {
        map.remove(path);
    }

    public boolean exists(String path) {
        return map.containsKey(path);
    }

    public void start() throws Exception {
        serverSocket = new ServerSocket(port);
        while (running) {
            Socket socket = serverSocket.accept();

            InputStream inputStream = socket.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String readLine = bufferedReader.readLine();
            if (readLine != null) {
                String[] readLineArr = readLine.split(" ");
                String path = readLineArr[1];

                System.out.println("readLine:" + readLine + ";path:" + path);

                // 输出
                OutputStream outputStream = socket.getOutputStream();
                if (path == null || "".equals(path) || "/".equals(path)) {
                    outputStream.write(formatHtmlHeader(200).getBytes());
                    outputStream.write("\r\n".getBytes());
                    outputStream.write(formatHtmlContent("welcome to OSGI").getBytes());
                } else if (map.containsKey(path)) {
                    outputStream.write(formatHtmlHeader(200).getBytes());
                    outputStream.write("\r\n".getBytes());
                    RequestHandler requestHandler = map.get(path);
                    outputStream.write(formatHtmlContent(requestHandler.handle()).getBytes());
                } else {
                    outputStream.write(formatHtmlHeader(404).getBytes());
                    outputStream.write("\r\n".getBytes());
                    outputStream.write(formatHtmlContent("404 not found").getBytes());
                }
            } else {
                System.err.println("readLine error");
            }

            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
        }
    }

    public void stop() throws IOException {
        running = false;

        serverSocket.close();
    }

    private String formatHtmlHeader(int status) {
        return "HTTP/1.1 " + status + " OK\r\n" +
                "Content-Type: text/html\r\n" +
                "Server: OSGI-Server/1.0.0\r\n";
    }

    private String formatHtmlContent(String content) {
        return "<html><body>\r\n" +
                content +
                "\r\n" +
                "</body></html>";
    }

    public static void main(String[] args) {
        try {
            HttpServer httpServer = new HttpServer();
            httpServer.addHandler("/home", () -> "welcome to home");
            httpServer.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
